/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 * @version 版本：1.0
 * @author 作者：lanjianwei 创建日期：2021-01-07
 */

package com.topscomm.mpm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.cbo.model.TreeModel;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.main.MPMApp;
import com.topscomm.main.hessian.IBaseOperateRecordService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.TapSystemConst.TapApprovalBillStateEnum;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.mpm.controller.auto.MpmProjectTaskControllerAuto;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;

/**
 * @author: lanjianwei
 * @date: 2021-01-07
 * @description:项目任务Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectTask")
public class MpmProjectTaskController extends MpmProjectTaskControllerAuto implements
    IMpmProjectTaskController {

    @Autowired
    private MpmProjectTaskFeedbackService mpmProjectTaskFeedbackService;
    @Autowired
    private MpmProjectMilepostService mpmProjectMilepostService;
    @Autowired
    private MpmProjectTaskCloseService mpmProjectTaskCloseService;
    @Resource(name = "mpmProjectTaskService")
    private MpmProjectTaskService mpmProjectTaskService;
    private Logger logger = LoggerFactory.getLogger(MpmProjectPolymerizationController.class);
    @Autowired
    private MpmProjectService mpmProjectService;
    @Autowired
    private IBaseOperateRecordService baseOperateRecordService;
    @Autowired
    private MpmPMOStandardizationRecordService mpmPMOStandardizationRecordService;

    /**
     * @author: lanjianwei
     * @date: 2021-01-07
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        String taskTableName = MpmProjectTaskEntity.tableName;
        sql.appendSingle(" {0}.enabled = 1 ", taskTableName);
        if (paraMap.containsKey("qry_responsible")) {
            String value = paraMap.get("qry_responsible").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and ({0}.responsiblecode = '{1}' or {0}.responsible like '%{1}%') ",
                        taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and ({0}.applyusercode = '{1}' or {0}.applyusername like '%{1}%') ",
                        taskTableName, value);
            }
        }
        // 任务状态查询条件
        if (paraMap.containsKey("qry_taskstate")) {
            String value = paraMap.get("qry_taskstate").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and taskstate in  ({0})", value);
            }
        }
        // 任务状态(增加超期)查询条件
        if (paraMap.containsKey("qry_taskstateindex")) {
            String value = paraMap.get("qry_taskstateindex").toString();
            if (!StringUtil.isEmpty(value)) {
                List<String> valueArr = new ArrayList<>(Arrays.asList(value.split(",")));
                List<String> templateArr = Arrays.asList(MpmSystemConst.TaskStateCode.TaskNotStartCode, MpmSystemConst.TaskStateCode.TaskIncompleteCode, MpmSystemConst.TaskStateCode.TaskOverdueCode);
                List<String> tempArr = valueArr.stream().filter(item -> !templateArr.contains(item)).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(tempArr)) {
                    sql.appendSingle(" and (1 != 1 ", value);
                } else {
                    String tempvalue = tempArr.stream().collect(Collectors.joining(","));
                    sql.appendSingle(" and (taskstate in ({0}) ", tempvalue);
                }
                if (value.contains(MpmSystemConst.TaskStateCode.TaskOverdueCode)) {
                    sql.appendSingle(" or (taskstate in ({0}) and {1} > {2} and MpmProjectTask.state = 9) ", MpmSystemConst.UndoneTaskCode, SQLAdapter.toChar(SQLAdapter.getDate() + ", 'yyyy-mm-dd'"), SQLAdapter.toChar(MpmProjectTaskEntity.FieldPlanenddate + ", 'yyyy-mm-dd'"));
                }
                if (value.contains(MpmSystemConst.TaskStateCode.TaskNotStartCode)) {
                    sql.appendSingle(" or (taskstate = {0} and ({1} <= {2} or MpmProjectTask.state = 0)) ", MpmSystemConst.TaskStateCode.TaskNotStartCode, SQLAdapter.toChar(SQLAdapter.getDate() + ", 'yyyy-mm-dd'"), SQLAdapter.toChar(MpmProjectTaskEntity.FieldPlanenddate + ", 'yyyy-mm-dd'"));
                }
                if (value.contains(MpmSystemConst.TaskStateCode.TaskIncompleteCode)) {
                    sql.appendSingle(" or (taskstate = {0} and ({1} <= {2} or MpmProjectTask.state = 0)) ", MpmSystemConst.TaskStateCode.TaskIncompleteCode, SQLAdapter.toChar(SQLAdapter.getDate() + ", 'yyyy-mm-dd'"), SQLAdapter.toChar(MpmProjectTaskEntity.FieldPlanenddate + ", 'yyyy-mm-dd'"));
                }
                sql.appendSingle(")");
            }
        }
        if (paraMap.containsKey("qry_responsiblecode")) {
            String value = paraMap.get("qry_responsiblecode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.responsiblecode = '{1}'", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_projectname")) {
            String value = paraMap.get("qry_projectname").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and projectname like '%{0}%'", value);
            }
        }
        if (paraMap.containsKey("qry_projectcode")) {
            String value = paraMap.get("qry_projectcode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.projectcode = '{1}' ", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_taskrisk")) {
            String value = paraMap.get("qry_taskrisk").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and exists (select id from mpmprojecttaskfeedback tfback where tfback.taskid = mpmprojecttask.id and tfback.taskrisk in ({0})) ", value);
            }
        }
        if (paraMap.containsKey("qry_milepostcode")) {
            String value = paraMap.get("qry_milepostcode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.milepostcode = '{1}'", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_milepostname")) {
            String value = paraMap.get("qry_milepostname").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.milepostname like '%{1}%'", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_taskname")) {
            String value = paraMap.get("qry_taskname").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and taskname like '%{0}%'", value);
            }
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.state={1}", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.docno like '%{1}%'", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.docdate >= {1} ",
                        taskTableName, SQLAdapter.toDateLong(value + " 00:00:00"));
            }
        }
        if (paraMap.containsKey("qry_taskid")) {
            String value = paraMap.get("qry_taskid").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.id = '{1}' ", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.docdate <= {1}", taskTableName, SQLAdapter.toDateLong(value + " 23:59:59"));
            }
        }
        if (paraMap.containsKey("qry_deptname")) {
            String value = paraMap.get("qry_deptname").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(
                        " and ({0}.deptid in ( SELECT id from CboDept where fullname like '%{1}%'))",
                        taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and ({0}.username like '%{1}%')", taskTableName, value);
            }
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0}.deptcode like '{1}%'", taskTableName, value);
            }
        }
        // 更新时间搜索条件，查找该时间跨度内更新任务反馈或差距与改进的项目
        if (paraMap.containsKey("qry_startdate") && paraMap.containsKey("qry_enddate")) {
            String startdate = ConvertUtil.convertToString(paraMap.get("qry_startdate"));
            String enddate = ConvertUtil.convertToString(paraMap.get("qry_enddate"));
            sql.appendSingle(" and exists (select * from mpmprojecttaskfeedback where submitdate between {0} and {1} and state = 9 and mpmprojecttaskfeedback.taskid = mpmprojecttask.id)"
                    , SQLAdapter.toDateShort(startdate), SQLAdapter.toDateShort(enddate));
        }
        // 手机端调用差距与改进查询
        if (paraMap.containsKey("qry_managercode")) {
            String value = ConvertUtil.convertToString(paraMap.get("qry_managercode"));
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and EXISTS (SELECT id FROM MPMPROJECT WHERE MPMPROJECT.PROJECTCODE = {0}.{1} and MPMPROJECT.PROJECTMANAGERCODE='{2}') ", MpmProjectTaskEntity.tableName, MpmProjectTaskEntity.FieldProjectcode, this.getUserBean().getUser().getCode());
            }
        }
        // 如果我的任务页面调用list接口，需要展示责任人或项目经理为本人的任务
        if (paraMap.containsKey("qry_resormanager")) {
            String value = ConvertUtil.convertToString(paraMap.get("qry_resormanager"));
            if ("2".equals(value)) {
                sql.appendSingle(" and ({0}.responsiblecode = '{1}' or EXISTS (SELECT id FROM MPMPROJECT WHERE MPMPROJECT.PROJECTCODE = {0}.{2} and MPMPROJECT.PROJECTMANAGERCODE='{1}')) ", taskTableName, this.getUserBean().getUser().getCode(), MpmProjectTaskEntity.FieldProjectcode);
            } else if ("1".equals(value)) {
                // 展示责任人为本人的任务
                sql.appendSingle(" and {0}.responsiblecode = '{1}' ", taskTableName, this.getUserBean().getUser().getCode());
            } else if ("0".equals(value)) {
                // 展示项目经理为本人的任务
                sql.appendSingle(" and EXISTS (SELECT id FROM MPMPROJECT WHERE MPMPROJECT.PROJECTCODE = {0}.{1} and MPMPROJECT.PROJECTMANAGERCODE='{2}') ", taskTableName, MpmProjectTaskEntity.FieldProjectcode, this.getUserBean().getUser().getCode());
            }
        }
        // 如果当前页面为监管页面
        if (paraMap.containsKey("qry_indexmytask")) {
            String chargeProvincesSql = getChargeProvinces(this.getUserBean().getUser().getCode());
            if (chargeProvincesSql.length() > 0) {
            if (paraMap.containsKey("qry_belongtype")) {
                chargeProvincesSql = "'" + chargeProvincesSql.replaceAll(",", "','") + "'";
                String value = ConvertUtil.convertToString(paraMap.get("qry_belongtype"));
                if (MpmSystemConst.BelongType.DUTY.equals(value)) {
                    sql.appendSingle(" and {0}.responsiblecode = '{1}' ", taskTableName, this.getUserBean().getUser().getCode());
                } else if (MpmSystemConst.BelongType.VIEW.equals(value)) {
                    // PMO 负责省区
                    sql.appendSingle(" and exists (select id from mpmproject where MPMPROJECT.PROJECTCODE = {0}.{1} and MPMPROJECT.deptcommoncode in ({2}) and MPMPROJECT.PROJECTLEVEL in ('0','1'))", taskTableName, MpmProjectTaskEntity.FieldProjectcode, chargeProvincesSql);
                } else {
                    // PMO 负责省区
                    sql.appendSingle(" and (exists (select id from mpmproject where MPMPROJECT.PROJECTCODE = {0}.{1} and MPMPROJECT.deptcommoncode in ({2}) and MPMPROJECT.PROJECTLEVEL in ('0','1'))", taskTableName, MpmProjectTaskEntity.FieldProjectcode, chargeProvincesSql);
                    // 责任人为本人的任务
                    sql.appendSingle(" or {0}.responsiblecode = '{1}' )", taskTableName, this.getUserBean().getUser().getCode());
                }
            } else {
                // PMO 负责省区
                sql.appendSingle(" and (exists (select id from mpmproject where MPMPROJECT.PROJECTCODE = {0}.{1} and MPMPROJECT.deptcommoncode in ({2}) and MPMPROJECT.PROJECTLEVEL in ('0','1'))", taskTableName, MpmProjectTaskEntity.FieldProjectcode, chargeProvincesSql);
                // 责任人为本人的任务
                sql.appendSingle(" or {0}.responsiblecode = '{1}' )", taskTableName, this.getUserBean().getUser().getCode());
             }
            }
        }
        // 如果检测到
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and taskname like '%{0}%' ", value);
            }
        }
        if (paraMap.containsKey("isoverdate")) {
            String isoverdate = (String) paraMap.get("isoverdate");
            //超期任务页面
            if ("1".equals(isoverdate)) {
                String timeNow = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
                sql.appendSingle(" and {0}.planenddate < {1}", taskTableName, SQLAdapter.toDateLong(timeNow));
                // qry_permission org公司，inChargeMe我负责的，participate我参与的 超期任务
                if (paraMap.containsKey("qry_permission")) {
                    String value = (String) paraMap.get("qry_permission");
                    sql.appendSingle("and " + mpmProjectService.whereExistsSqlForIndex("MpmProjectTask", "projectcode", value));
                }
            }
        }
        if (paraMap.containsKey("qry_submithundred")) {
            String value = paraMap.get("qry_submithundred").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and not exists (select id from mpmprojecttaskfeedback tfback where tfback.taskid = mpmprojecttask.id and tfback.taskschedule = '100') ");
            }
        }
        if (paraMap.containsKey("queryType")) {
            String value = ConvertUtil.convertToString(paraMap.get("queryType"));
            if ("0".equals(value)) {
                sql.appendSingle(" and planenddate < {0} - 1 ", SQLAdapter.getDate());
            }
        }
        /*		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
				if (StringUtil.isEmpty(deptcodes_header))
					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
							.getUserBean().getWorkDept().getCode());
				else
					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}*/
        return sql.toString();
    }
     /**
      * @Description:    获取经营管理部PMO管理的省份code处理sql
      * @Author:         wuyuyang
      * @Return:         java.lang.String
      * @exception:
      * @Date:           22/5/2023 下午2:55
      * @Version:        1.0
      **/
    private String getChargeProvinces(String usercode) {
        StringBufferProxy codeSql = new StringBufferProxy();
        codeSql.appendSingle(" usercode = '{0}' and enabled = 1 ", usercode);
        List<MpmPMOStandardizationRecordEntity> res = mpmPMOStandardizationRecordService.queryByWhere(codeSql.toString());
        if (CollectionUtil.isEmpty(res)) {
            return "";
        }
        return res.get(0).getChargedeptcommoncode();
    }


    @PostMapping(value = "/exportExcel")
    public void exportExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request,
                            HttpServletResponse response) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
            String sord = ConvertUtil.convertToString(paraMap.get("sord"));
            String cols = ConvertUtil.convertToString(paraMap.get("cols"));
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(spellListSql(paraMap));
            if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
                sql.appendSingle(" order by {0} {1} ", sidx, sord);
            }
            List<Map<String, Object>> listDataMap = this.service.queryMapByWhere(sql.toString());
            listDataMap.stream().forEach(m -> {
                if(ConvertUtil.convertToString(m.get("taskschedule")).length() != 0){
                    m.put("taskschedule", ConvertUtil.convertToString(m.get("taskschedule")) + "%");
                }
            });
            // 如果projectlist的个数>1000，则将projectlist按照1000分成多个List
            List<List<Map<String, Object>>> splitList = mpmProjectTaskService.splitInList(listDataMap);
            for (List<Map<String, Object>> tempList : splitList) {
                this.service.getProjectInfo(tempList);
            }
            String[] colArray = cols.split(",");
            InputStream inStream = OfficeOperateUtil.exportExeclXlsx(listDataMap, colArray);
            String fileName = "导出数据.xlsx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inStream.close();
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage(), true);
        }
    }


    @Override
    @GetMapping({"/list"})
    public ResponseResult<Object> list(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            List<Map<String, Object>> tempList = null;
            Map<String, Object> paraMap2 = new HashMap<>();
            paraMap2.put("curPageIndex", query.getCurrentPage());
            int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
            paraMap2.put("begincount", beginCount);
            paraMap2.put("pagesize", query.getPageSize());
            paraMap2.put("sidx", query.getSidx());
            paraMap2.put("sord", query.getSord());
            paraMap2.put("whereSql", sqlWhere);
            int totalCount = this.service.getCount1(paraMap2, "getMapByWhere");
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(paraMap2, "getMapForPage");
            } else {
                tempList = this.service.queryMap(paraMap2, "getMapByWhere");
            }
            if (CollectionUtils.isEmpty(tempList)) {
                return ResponseResult.ok(new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage()));
            }
            this.service.getProjectInfo(tempList);
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }


    /**
     * @author: lanjianwei
     * @date: 2021-01-07
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellRefListSql(paraMap);
//            StringBufferProxy str = new StringBufferProxy();
//            str.appendSingle("{0} and responsiblecode = {1}", sqlWhere, ConvertUtil.convertToString(paraMap.get("currentUser")));
            int totalCount = this.service.getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = this.service.queryMapByWhere(sqlWhere);
            }
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
    }

    /**
     * @Title: insertFromProject
     * @description: 按照项目插入任务
     * @param paraMap
     * @return
     * @author: lanjianwei
     * @date: 2021年1月12日下午5:22:14
     * @modify:
     */
    @PostMapping(value = "/insertFromProject")
    public ResponseResult<Object> insertFromProject(
            @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            ResponseResult responseResult = mpmProjectTaskService.insertFromProject(paraMap);
            return responseResult;
        } catch (Exception ex) {
            logger.info(ex.getMessage());
            return ResponseResult.error("插入项目任务出错，请联系管理员!");
        }
    }

    /**
     * @Title: insertFromTaskTemplate
     * @description:按照模板插入任务
     * @param paraMap
     * @return
     * @author: lanjianwei
     * @date: 2021年1月14日下午6:19:51
     * @modify:
     */
    @PostMapping(value = "/insertFromTaskTemplate")
    public ResponseResult<Object> insertFromTaskTemplate(
            @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            ResponseResult responseResult = mpmProjectTaskService.insertFromTaskTemplate(paraMap);
            return responseResult;
        } catch (Exception ex) {
            logger.info(ex.getMessage());
            return ResponseResult.error("插入项目任务出错，请联系管理员!");
        }
    }

    /**
     * @Title: startTask
     * @description:开始任务
     * @param paraMap
     * @return
     * @author: lanjianwei
     * @date: 2021年1月14日下午6:20:52
     * @modify:
     */
    @PostMapping(value = "/start")
    public ResponseResult<Object> startTask(
            @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            ResponseResult responseResult = mpmProjectTaskService.startTask(paraMap);
            return responseResult;
        } catch (Exception ex) {
            logger.info(ex.getMessage());
            return ResponseResult.error("开始项目任务出错，请联系管理员!");
        }
    }

    /**
     * @Title: startTask
     * @description:首页我的任务数量
     * @param paraMap
     * @return
     * @author: lanjianwei
     * @date: 2021年1月14日下午6:20:52
     * @modify:
     */
    @GetMapping(value = "/myTaskCount")
    public ResponseResult<Object> myTaskCount(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            int count = mpmProjectTaskService.getCount(spellListSql(paraMap));
            return ResponseResult.ok(count);
        } catch (Exception ex) {
            StackTraceElement[] stackTrace = ex.getStackTrace();
            for (StackTraceElement item : stackTrace) {
                logger.info(item.toString());
            }
            logger.info(ex.getMessage());
            return ResponseResult.error("我的任务查询出错，请联系管理员!");
        }
    }

    /**
     * @Title:
     * @description: 更新进行中的任务责任人
     * @param paraMap
     * @return
     * @author:
     * @date:
     * @modify:
     */
    @PutMapping(value = "/updateResponsible")
    public ResponseResult<Object> updateResponsible(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            MpmProjectTaskEntity mpmProjectTaskEntity = this.service.queryById(ConvertUtil.convertToString(paraMap.get("id")));
            mpmProjectTaskEntity.setResponsible(ConvertUtil.convertToString(paraMap.get("responsible")));
            mpmProjectTaskEntity.setResponsiblecode(ConvertUtil.convertToString(paraMap.get("responsiblecode")));
            this.service.updateEntity(mpmProjectTaskEntity);
            return ResponseResult.ok("修改成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }
    /**
     * @Title:
     * @description:获取该任务的进度更新
     * @param paraMap
     * @return
     * @author: houyuhang
     * @date: 2021年11月3日
     * @modify:
     */
    @GetMapping(value = "/queryTaskFeedbackList")
    public ResponseResult<Object> queryTaskFeedbackList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        String taskid = ConvertUtil.convertToString(paraMap.get("taskid"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("taskid = '{0}' and state < 9 and istaskfeedback = '1' ", taskid);
        List<MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntityList = mpmProjectTaskFeedbackService.queryByWhere(sql.toString());
        return ResponseResult.ok(mpmProjectTaskFeedbackEntityList);
    }
    /**
     * @Title:
     * @description:获取该任务的任务关闭信息
     * @param paraMap
     * @return
     * @author: houyuhang
     * @date: 2021年12月04日
     * @modify:
     */
    @GetMapping(value = "/queryTaskCloseList")
    public ResponseResult<Object> queryTaskCloseList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        String taskid = ConvertUtil.convertToString(paraMap.get("taskid"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("taskid = '{0}' and state < 9", taskid);
        List<MpmProjectTaskCloseEntity> mpmProjectTaskCloseEntityList = mpmProjectTaskCloseService.queryByWhere(sql.toString());
        return ResponseResult.ok(mpmProjectTaskCloseEntityList);
    }
    /**
     * @Title:
     * @description:去除里程碑及任务未置为可用的任务
     * @param tempList
     * @return
     * @author: houyuhang
     * @date: 2022年01月15日
     * @modify:
     */
    List<Map<String,Object>> filterMilepostDisabled(List<Map<String, Object>> tempList) {
        List<Map<String, Object>> temp = new ArrayList<>(tempList);
        String milepostCode = temp.stream().map(item -> ConvertUtil.convertToString(item.get("milepostcode")))
                .collect(Collectors.joining(","));
        if(StringUtil.isEmpty(milepostCode)) {
            return tempList;
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" operatecode in ({0}) ", milepostCode);
        // 获取任务对应的所有里程碑及任务信息
        List<MpmProjectMilepostEntity> milepostList = mpmProjectMilepostService.queryByWhere(sql.toString());
        Map<String,Boolean> operateCodeMap = new HashMap<>();
        // 确认里程碑及任务enabled值是否为1
        milepostList.forEach(milepost -> {
            if(milepost.getEnabled() == 1) {
                operateCodeMap.put(ConvertUtil.convertToString(milepost.getOperatecode()),true);
            }
        });
        // 去除任务List中里程碑及任务enabled值为0的任务
        tempList = tempList.stream().filter(item -> operateCodeMap.get(ConvertUtil.convertToString(item.get("milepostcode"))) != null).collect(Collectors.toList());
        return tempList;
    }

    /**
     * @Title:
     * @description: 下发任务并给任务责任人、里程碑及任务责任人发送消息提醒
     * @param
     * @return
     * @author: zhangjunyao
     * @date: 2022年03月17日
     * @modify:
     */
    @PutMapping(value = "/distributeTask")
    public ResponseResult<Object> distributeTask(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            // 单独下发时参数为id
            if (paraMap.containsKey("id")) {
                this.service.distributeTask(ConvertUtil.convertToString(paraMap.get("id")));
                return ResponseResult.ok("下发成功！");
            }
            // 批量下发时参数为idlist
            if (paraMap.containsKey("idlist")) {
                // object转化为list
                List<String> idsList = new ArrayList<>();
                Object tempList = paraMap.get("idlist");
                for (Object o : (List<?>) tempList) {
                    idsList.add(ConvertUtil.convertToString(o));
                }
                for (String taskId : idsList) {
                    this.service.distributeTask(taskId);
                }
                return ResponseResult.ok("批量下发成功！");
            }
            return ResponseResult.error("获取任务失败，请联系管理员。");
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }
    /**
     * @Title:
     * @description:系统部监管页面获取客户决策分析数据
     * @param paraMap
     * @return
     * @author: houyuhang
     * @date: 2022年03月26日
     * @modify:
     */
    @GetMapping(value = "/queryTaskForSystem")
    public ResponseResult<Object> queryTaskForSystem(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String,Object>> res = this.service.queryTaskForSystem(paraMap);
            res = baseOperateRecordService.getMarkedData(res,MpmProjectTaskEntity.tableName,getUserBean().getUser().getCode());
            return ResponseResult.ok(res);
        } catch (Exception ex) {
            return ResponseResult.error("加载任务出错，请联系管理员!");
        }
    }
    /**
     * @Title:
     * @description: 重写datacodelist
     * @param paraMap
     * @return
     * @author: houyuhang
     * @date: 2022年04月06日
     * @modify:
     */
    @Override
    @GetMapping(value = "/dataCodeList")
    public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        ResponseResult<Object> res = super.dataCodeList(paraMap);
        Map<String, Object> codeMap = (Map<String, Object>) res.getResult();
        List<Map<String, Object>> mpmSystemTasknameList = datacodeCache.getCodeListMap("MpmSystemTaskname", "", "sortcode");
        codeMap.put("mpmsystemtasknameList", mpmSystemTasknameList);
        List<Map<String, Object>> taskriskList = datacodeCache.getCodeListMap("MpmProjectTaskRisk", "", "sortcode");
        codeMap.put("taskriskList", taskriskList);
        return ResponseResult.ok(codeMap);
    }

    @GetMapping(value = "/listForTrack")
    public ResponseResult<Object> listForTrack(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            List<Map<String, Object>> tempList = null;
            HashMap<String, Object> paraMap2 = new HashMap<>();
            paraMap2.put("curPageIndex", query.getCurrentPage());
            int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
            paraMap2.put("begincount", beginCount);
            paraMap2.put("pagesize", query.getPageSize());
            paraMap2.put("sidx", query.getSidx());
            paraMap2.put("sord", query.getSord());
            paraMap2.put("whereSql", sqlWhere);
            int totalCount = this.service.getCount1(paraMap2, "getMapByWhere");
            // 获取全部任务，在后台实现按照任务编号排序
            tempList = this.service.queryMap(paraMap2, "getMapByWhere");
            if (CollectionUtils.isEmpty(tempList)) {
                return ResponseResult.ok(new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage()));
            }
            tempList = this.service.generateTaskcode(tempList, paraMap);
            tempList = tempList.stream().skip(beginCount).limit(query.getPageSize()).collect(Collectors.toList());
            for (int i = 0;i< tempList.size();i++) {
                tempList.get(i).put("rowno", i+1);
            }
            this.service.getProjectInfo(tempList);
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }
    /**
     * @author: houyuhang
     * @date: 2023-04-11
     * @param paraMap
     * @return
     * @description: 获取任务reflist，增加任务编号
     * @modify:
     */
    @GetMapping(value = "/refListForTrack")
    public ResponseResult<Object> refListForTrack(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellRefListSql(paraMap);
            paraMap.put("whereSql", sqlWhere);
            int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
            int totalCount = this.service.getCount1(paraMap, "getMapByWhere");
            List<Map<String, Object>> tempList = null;
            // 获取筛选条件下的全部任务，不使用sql进行分页，在后台实现按照任务编号排序
            tempList = this.service.queryMap(paraMap, "getMapByWhere");
            if (CollectionUtils.isEmpty(tempList)) {
                return ResponseResult.ok(new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage()));
            }
            tempList = this.service.generateTaskcode(tempList, paraMap);
            tempList = tempList.stream().skip(beginCount).limit(query.getPageSize()).collect(Collectors.toList());
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 树查询方法
     * @param paraMap
     * @return
     * @author: houyuhang
     * @date: 2022-11-10
     * @modify:
     */

    @GetMapping(value = "/queryTreeList")
    public ResponseResult<Object> queryTreeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        // 生成策划、里程碑、任务三级树
        List<Map<String, Object>> listNewModule = mpmProjectTaskService.queryTreeList(paraMap);
        TreeModel treeModel = new TreeModel();
        List<TreeModel> treeList = treeModel.buildTree(listNewModule, true, "策划");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", treeList);
        return ResponseResult.ok(dataMap);
    }
}

